package com.okaixz.client.service.impl;

import cn.hutool.core.util.IdUtil;
import com.okaixz.client.model.domain.User;
import com.okaixz.client.model.dto.JwtUser;
import com.okaixz.client.model.dto.UserDto;
import com.okaixz.client.service.ITokenService;
import com.okaixz.client.service.IUserService;
import com.okaixz.common.core.redis.RedisCache;
import com.okaixz.common.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author cdz
 * @since 2024-10-08
 */
@Service
@Slf4j
public class TokenServiceImpl implements ITokenService {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IUserService userService;


    @Override
    public UserDto getTokenUser(String token) {
        JwtUser jwtUser = JwtUtil.parseToken(token, JwtUser.class);
        if (jwtUser == null) {
            //过期返回空
            return null;
        }
        String userId = jwtUser.getUserId();
        User user = userService.getUserFromRedis(userId);
        if (user == null) {
            //缓存没有需要重建
            return null;
        }
        String nanoid = user.getNanoid();
        String salt = jwtUser.getSalt();

        log.info("userId:{},nanoid:{},salt:{}",userId,nanoid,salt);
        if (salt == null) {
            return null;
        }
        //如果nanoid和redis保存的salt一致续签token过期时间
        if (nanoid!=null&&nanoid.equals(salt)) {
            UserDto userDto=new UserDto();
            BeanUtils.copyProperties(user,userDto);
            return userDto;
        }
        //如果nanoid和redis保存的salt不一致返回空
        return null;
    }

    @Override
    public UserDto refreshUserAndToken(String userId) {
        User user = userService.getUserFormRedisOrDb(userId);//从缓存或数据库获取用户信息

        String nanoId = IdUtil.nanoId(8);
        user.setNanoid(nanoId);
        userService.saveUserToRedis(user);//将用户信息放到缓存

        UserDto userDto=new UserDto();
        BeanUtils.copyProperties(user,userDto);
        log.info("user={}",user.toString());
        log.info("userDto={}",userDto.toString());

        String token = getToken(user);
        userDto.setToken(token);
        log.error("刷新token了={}",userDto.getToken());
        return userDto;
    }

    @Override
    public String getToken(User user) {
        JwtUser jwtUser=new JwtUser();
        jwtUser.setUserId(user.getUserId());
        jwtUser.setSalt(user.getNanoid());
        String token = JwtUtil.getToken(jwtUser);
        return token;
    }
}
